<?php

namespace App\Models;

use App\Models\Scope\OnSaleScope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Product extends Model
{
    use SoftDeletes;

    const TYPE_SECKILL = 'seckill';
    const TYPE_NORMAL = 'normal';

    protected $fillable = [
        'type'
    ];

    protected static function boot()
    {
        parent::boot();

        //查询作用域
        static::addGlobalScope(new OnSaleScope());
    }

    public function spec()
    {
        return $this->belongsToMany(Spec::class, 'product_spec_value_rels', 'product_id', 'spec_id');
    }

    /**
     * 关联秒杀商品
     */
    public function seckill()
    {
        return $this->belongsToMany(ProductSeckill::class,'product_seckill_middle','product_id','seckill_id');
    }

    /**
     * 关联产品优惠券
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function coupons()
    {
        return $this->belongsToMany(Coupon::class,'product_coupons_middles','product_id','coupon_id');
    }

    /**
     * 关联商品图册
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function images()
    {
        return $this->hasMany(ProductImages::class,'product_id','id');
    }

    // 关联sku
    public function skus()
    {
        return $this->hasMany(ProductSku::class);
    }

    // 关联商品规格关系表
    public function specRel()
    {
        return $this->belongsToMany(SpecValue::class, 'product_spec_value_rels', 'product_id', 'spec_value_id');
    }

    public function orderItems()
    {
        return $this->belongsTo(OrderItem::class);
    }
    /**
     * 关联运费
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function freight()
    {
        return $this->hasOne(Freight::class,'id','freight_id');
    }

    // 获取产品服务
    public function getServerIdAttribute($value)
    {
        if($value)
        {
            return $this->attributes['server_id'] = ProductService::whereIn('id', explode(',', $value))->get();
        }
        return [];
    }

    public function getImageAttribute($value)
    {
        if($value && !Str::contains($value, config('upload.ossUrl')))
        {
            return $this->attributes['image'] = config('upload.ossUrl').$value;
        } elseif (Str::contains($value, config('upload.ossUrl'))) {
            return $this->attributes['image'] = $value;
        } else {
            return $this->attributes['image'] = '';
        }
    }

    public function getPriceAttribute($value)
    {
       return floatval($value);
    }

    // 获取实时库存
    public function getStockCountAttribute()
    {
        return $this->skus()->sum('stock');
    }

    public function address()
    {
        return $this->hasOne(ProductAddress::class,'id','return_address_id');
    }

    // 计算分销后的预计金额 （商品详情展示）
    public function getDistributionAmountAttribute()
    {
        $commissionRatio = $this->commission_ratio;

        if ($commissionRatio > 0) {

            $prices = $this->skus()->get()->map(function ($item) use ($commissionRatio) {
                // 计算每个sku 应该得到到分销金额
                return $item->price * bcdiv($commissionRatio,100,2);
            })->sort();
            if ($prices->first() == $prices->last()) {
               return floatval(bcadd($prices->first(), 0, 2));
            }
            return $prices->first().'~'.$prices->last();
        }
        return '';
    }

    // 商品是否包邮
    public function getIsShippingAttribute(){
        $freight = $this->freight()->first();
        if ($freight) {
           if ($freight->freight_price > 0) {
               return false;
           } else {
               return true;
           }
        }
        return true;
    }
}
